package zzq.upload;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import zzq.util.FtpAction;
import zzq.util.Properties;

import java.io.*;

public class UploadFtpLogAction implements FtpAction {


    @Override
    public FTPClient login(Properties properties) {
        FTPClient ftpClient = new FTPClient();
        try {
//            ftpClient.setConnectTimeout(2000);
            ftpClient.connect(properties.getHost(), properties.getPort());
            ftpClient.login(properties.getUserName(), properties.getPassword());
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("登录成功");
                return ftpClient;
            }   else {
                System.out.println("登录失败");
                return null;
            }

        } catch (IOException e) {
            System.out.println("无法连接到Ftp服务器");
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean uploadFile(String localFilePathAndName, String remoteDir, FTPClient client) {
        if (!client.isAvailable()) {
            return false;
        }
        File file = new File(localFilePathAndName);
        if (!file.exists()) {
            System.out.println("文件不存在");
        }
        try {
            String encoding = "GBK";
            try {
                if (FTPReply.isPositiveCompletion(client.sendCommand("OPTS UTF8", "ON"))) {
                    encoding = "UTF-8";
                }else {
                    System.out.println("不支持");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            client.setControlEncoding(encoding);
            InputStream stream = new FileInputStream(file);
            String fileName0 = "zzq_" + file.getName();
            String fileName = new String(fileName0.getBytes(encoding),
                    SERVER_CHARSET);
//            boolean b = client.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), stream);
            boolean b = client.storeFile(fileName, stream);
            stream.close();
            if (b) {
                System.out.println(fileName0 + "  已经成功上传");
                return true;
            }else {
                System.out.println(fileName0 + "  上传失败");
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

}
